<template>
  <div class="page-wrapper form-designer-grid">
    <vxe-layout-container>
      <vxe-layout-body>
        <vxe-tabs
          v-model="selectTab"
          :options="tabList"
          :close-config="closeConfig"
          @tab-close="tabCloseEvent"
          @tab-close-fail="tabCloseFailEvent"
        >
          <template #extra>
            <!--            <vxe-pulldown-->
            <!--              :options="tabOptions"-->
            <!--              trigger="click"-->
            <!--              show-popup-shadow-->
            <!--              transfer-->
            <!--              @option-click="tabOptionClickEvent"-->
            <!--            >-->
            <!--              <template #default>-->
            <!--                <vxe-button mode="text" content="新增视图" status="primary" icon="vxe-icon-add" />-->
            <!--              </template>-->
            <!--            </vxe-pulldown>-->

            <el-dropdown :hide-on-click="true">
              <span class="el-dropdown-link cursor-pointer form-designer-add-view">
                <el-icon size="20px" title="新增视图"><Plus /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-icon>
                      <Memo />
                    </el-icon>
                    表格
                  </el-dropdown-item>
                  <el-dropdown-item disabled>
                    <el-icon>
                      <Memo />
                    </el-icon>
                    看板
                  </el-dropdown-item>
                  <el-dropdown-item disabled>
                    <el-icon>
                      <Calendar />
                    </el-icon>
                    日历
                  </el-dropdown-item>
                  <el-dropdown-item disabled>
                    <el-icon>
                      <Orange />
                    </el-icon>
                    画廊
                  </el-dropdown-item>
                  <el-dropdown-item disabled>
                    <el-icon>
                      <Postcard />
                    </el-icon>
                    详情
                  </el-dropdown-item>
                  <el-dropdown-item disabled>
                    <el-icon>
                      <Memo />
                    </el-icon>
                    层级
                  </el-dropdown-item>
                  <el-dropdown-item disabled>
                    <el-icon>
                      <MapLocation />
                    </el-icon>
                    地图
                  </el-dropdown-item>
                  <el-dropdown-item disabled>
                    <el-icon>
                      <Memo />
                    </el-icon>
                    甘特图
                  </el-dropdown-item>
                  <el-dropdown-item disabled>
                    <el-icon>
                      <CopyDocument />
                    </el-icon>
                    资源
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </vxe-tabs>
        <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents" />
      </vxe-layout-body>
      <vxe-layout-aside vertical class="form-designer-sidebar">
        <vxe-layout-container vertical>
          <vxe-layout-header fixed class="bg1">
            <vxe-tag class="title">列表配置属性</vxe-tag>
          </vxe-layout-header>
          <vxe-layout-body class="bg3">
            <div style="height: 400px">内容</div>
          </vxe-layout-body>
          <vxe-layout-footer fixed class="bg4">
            <span>底部</span>
          </vxe-layout-footer>
        </vxe-layout-container>
      </vxe-layout-aside>
    </vxe-layout-container>
  </div>
</template>

<script lang="ts" setup>
import { VxeGridInstance, VxeGridListeners, VxeGridProps, VxeTableDefines } from 'vxe-table'
import { useApprovalDesignerStore } from '@/store/modules/dsgn/ApprovalDesigner'
import { FormCreateRule2Tbl } from '@/api/res/FormDsgn/DataTable/DataTable'
import { VxeTabsPropTypes, VxeUI } from 'vxe-pc-ui'
import { findIndex } from '@/utils'
import {
  Plus,
  Memo,
  DocumentAdd,
  Calendar,
  Orange,
  Postcard,
  MapLocation,
  CopyDocument
} from '@element-plus/icons-vue'
// const formDsgnStore = useFormDesignerStore()
// const { designerModelForm } = useApprovalDesignerStore()
const gridRef = ref<VxeGridInstance>()

interface RowVO {
  id: number | string
}

const selectTab = ref('1')

const tabList = ref<VxeTabsPropTypes.Options>([
  { name: '1', title: '默认视图', icon: 'vxe-icon-home' },
  { name: '2', title: '标题2' },
  { name: '3', title: '标题3标题3标题3' },
  { name: '4', title: '标题4标题4' },
  { name: '5', title: '标题5标题5标题5' }
])

const tabOptions = ref([
  { label: '表格', value: 'table' },
  { label: '看板', value: 'kanban' },
  { label: '日历', value: 'calendar' },
  { label: '画廊', value: 'gallery' },
  { label: '详情', value: 'detail' },
  { label: '层级', value: 'tree' },
  { label: '地图', value: 'map' },
  { label: '甘特图', value: 'gantt' },
  { label: '资源', value: 'resource' }
])

const tabOptionClickEvent = ({ option }) => {
  const index = findIndex(tabList.value, (item) => item.name === selectTab.value)
  switch (option.value) {
    case 'closeOther':
      tabList.value = tabList.value.filter((item) => item.name === selectTab.value)
      break
    case 'closeLeft':
      tabList.value = tabList.value.slice(index)
      break
    case 'closeRight':
      tabList.value = tabList.value.slice(0, index + 1)
      break
    case 'refresh':
      VxeUI.modal.message({
        content: '刷新页面',
        status: 'success'
      })
      break
  }
}

const closeConfig = ref<VxeTabsPropTypes.CloseConfig>({
  enabled: true,
  beforeMethod() {
    // 支持同步或异步
    return VxeUI.modal
      .confirm({
        content: '请确认是否关闭？'
      })
      .then((type) => {
        if (type === 'confirm') {
          return true
        }
        return false
      })
  }
})

const tabCloseEvent: VxeTabsEvents.TabClose = ({ name, nextName }) => {
  VxeUI.modal.message({
    content: '已关闭',
    status: 'success'
  })
  tabList.value = tabList.value.filter((item) => item.name !== name)
  selectTab.value = nextName
}

const tabCloseFailEvent: VxeTabsEvents.TabCloseFail = () => {
  VxeUI.modal.message({
    content: '阻止关闭',
    status: 'warning'
  })
}

const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: true,
  stripe: true,
  loading: false,
  height: 400,
  // 自定义工具栏
  toolbarConfig: {
    zoom: {
      iconIn: 'vxe-icon-fullscreen',
      iconOut: 'vxe-icon-minimize'
    },
    custom: {
      icon: 'vxe-icon-layout'
    },
    tools: [
      {
        title: '同步表单列表结构',
        code: 'columnRefresh',
        circle: true,
        // status: 'success',
        icon: 'vxe-icon-repeat'
      },
      {
        title: '同步表单列表结构并刷新数据',
        code: 'columnAndDataRefresh',
        circle: true,
        icon: 'vxe-icon-refresh'
      }
    ]
    // buttons: [
    //   { name: '新增', code: 'myAdd', status: 'primary' },
    //   { name: '删除', code: 'myDel', status: 'error' },
    //   { name: '保存', code: 'mySave', status: 'success' }
    // ]
  },
  pagerConfig: {
    enabled: true,
    pageSize: 15
  },
  proxyConfig: {
    props: {
      result: 'result',
      total: 'page.total'
    },
    ajax: {
      // 接收 Promise
      query: ({ page }) => {
        return fetchApi(page.currentPage, page.pageSize)
      }
    }
  },
  customConfig: {
    mode: 'drawer',
    storage: true,
    restoreStore({ id }) {
      return findCustomSetting(id)
    },
    updateStore({ id, storeData }) {
      // 模拟异步，实现服务端保存
      return saveCustomSetting(id, storeData)
    }
  },
  columnConfig: {
    drag: true,
    resizable: true
  },
  rowConfig: {
    isHover: true
  },
  checkboxConfig: {
    labelField: 'id',
    highlight: true,
    range: true
  },
  columns: [],
  data: []
})

// 模拟后台接口
const fetchApi = (currentPage: number, pageSize: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const list = [
        {
          id: 10001,
          name: 'Test1',
          nickname: 'T1',
          role: 'Develop',
          sex: 'Man',
          age: 28,
          address: 'Shenzhen'
        },
        {
          id: 10002,
          name: 'Test2',
          nickname: 'T2',
          role: 'Test',
          sex: 'Women',
          age: 22,
          address: 'Guangzhou'
        }
      ]
      resolve({
        page: {
          total: list.length
        },
        result: list.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      })
    }, 100)
  })
}

const gridEvents: VxeGridListeners<RowVO> = {
  custom({ type }) {
    debugger
    console.log(type)
  },
  toolbarButtonClick({ code }) {
    debugger
    const $grid = gridRef.value
    if ($grid) {
      switch (code) {
        case 'myInsert': {
          $grid.insert({
            name: 'xxx'
          })
          break
        }
        case 'mySave': {
          const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()
          // VxeUI.modal.message({ content: `新增 ${insertRecords.length} 条，删除 ${removeRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'success' })
          break
        }
        case 'myExport': {
          $grid.exportData({
            type: 'csv'
          })
          break
        }
      }
    }
  },
  toolbarToolClick({ code }) {
    const $grid = gridRef.value
    if ($grid) {
      switch (code) {
        case 'columnRefresh':
          loadColumConfig()
          break
        case 'columnAndDataRefresh':
          loadColumData()
          break
      }
    }
  }
}

// /** 初始化 **/
// onBeforeUpdate(async () => {
//   loadColumConfig()
// })
//
// onMounted(() => {
//   loadColumConfig()
// })

const loadColumConfig = () => {
  debugger
  const { getDsgnModelFormConfigJson } = useApprovalDesignerStore()
  const widgetRules = getDsgnModelFormConfigJson.widgetList
  gridOptions.columns = FormCreateRule2Tbl(widgetRules)
}

// 模拟查询接口
const findCustomSetting = (id: string) => {
  return new Promise<VxeTableDefines.CustomStoreData>((resolve) => {
    setTimeout(() => {
      try {
        if (sessionStorage.getItem(id)) {
          resolve(JSON.parse(sessionStorage.getItem(id) || '') as VxeTableDefines.CustomStoreData)
          // VxeUI.modal.message({
          //   status: 'success',
          //   content: '异步还原用户个性化数据成功'
          // })
        } else {
          resolve({})
        }
      } catch (e) {
        resolve({})
      }
    }, 500)
  })
}

// 模拟保存接口
const saveCustomSetting = (id: string, storeData: VxeTableDefines.CustomStoreData) => {
  return new Promise<void>((resolve) => {
    setTimeout(() => {
      console.log(storeData)
      sessionStorage.setItem(id, JSON.stringify(storeData))
      // VxeUI.modal.message({
      //   status: 'success',
      //   content: '保存用户个性化数据成功'
      // })
      resolve()
    }, 200)
  })
}

const loadColumData = () => {
  // 模拟后台接口
  gridOptions.loading = true
  setTimeout(() => {
    loadColumConfig()
    gridOptions.data = [
      { id: 10001, name: 'Test1', role: 'Develop', sex: 'Man', age: 28, address: 'test abc' },
      { id: 10002, name: 'Test2', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
      { id: 10003, name: 'Test3', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
      { id: 10004, name: 'Test4', role: 'Designer', sex: 'Women', age: 24, address: 'Shanghai' }
    ]
    gridOptions.loading = false
  }, 500)
}
</script>

<style lang="scss">
.form-designer-grid {
  .vxe-tools--wrapper {
    margin-right: 10px;
  }
}

.form-designer-add-view {
  margin: 0 7px;
}
</style>
